package com.redistest.seckill.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redistest.seckill.mapper.UserMapper;
import com.redistest.seckill.pojo.User;
import com.redistest.seckill.service.IUserService;
import com.redistest.seckill.utils.PasswordUtils;
import com.redistest.seckill.vo.Result;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2025-04-06
 */
@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String , Object> redisTemplate;

    @Override
    public Result Login(String nickname, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("nickname", nickname);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return Result.error(400, null, "用户不存在");
        } else {
            if (PasswordUtils.checkPassword(password, user.getPassword()) == false) {
                return Result.error(400, null, "用户名或密码错误");
            }else {
                //生成token
                String token= UUID.randomUUID()+"";
                //存Redis数据库
                redisTemplate.opsForValue().set("user:"+token, JSON.toJSONString(user), Duration.ofHours(24));
                return Result.success(token,"登录成功");
            }
        }
    }

    @Override
    public User getUserByToken(String token, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtil.isNullOrEmpty(token)) {
            return null;
        }
        User user=(User) redisTemplate.opsForValue().get("user:"+token);
        if (user != null) {
            System.out.println(JSON.toJSONString(user));
        }
        return user;
    }

}
